/**
 * browser platform is necessary
 * call by N just like $ in jquery
 * author: NeuronLink
 */

(function(platform, call) {
    // type
    function is_prototype(data) {
      return Object.prototype.toString.call(data).toLowerCase();
    }
  
    function is_object(data) {
      return is_prototype(data) === '[object object]';
    }
  
    function is_function(data) {
      return is_prototype(data) === '[object function]';
    }
  
    function is_urlsearchparams(data) {
      return is_prototype(data) === '[object urlsearchparams]';
    }
  
    function encap_data(d) {
      return d;
    }
  
    function encap_params(p) {
      return p;
    }
  
    function get(url, ajax, encap) {
      ajax = ajax || axios;
      encap = encap || encap_params;
      return function(params) {
        params = params || {};
        return ajax.get(url, {params: encap(params)})
      };
    }
  
    function post(url, ajax, encap) {
      ajax = ajax || axios;
      encap = encap || encap_data;
      return function(data) {
        data = data || {};
        return ajax.post(url, encap(data))
      };
    }
    // @param: interceptors[Array<Function, Function>]
    function createAjax(baseURL, options, interceptors) {
      options = options || {};
      var ajax = axios.create({
        baseURL: baseURL,
        timeout: options.timeout || 30000, // 7.31号修改为30秒
        headers: options.headers,
        auth: options.auth,
        withCredentials: options.withCredentials,
        transformRequest: [
          function(data, headers) {
            // handle in encap
            return data;
          }],
        transformResponse: [
          function(data) {
            // transform res data here
            if (!is_object(data)) {
              try {
                data = JSON.parse(data);
              } catch (e) {
                data = data || {};
              }
            }
            try {
              // intercept not login
            //   if (data.code === 806 && location.href.indexOf('login') === -1) {
            //       sessionStorage.clear();
            //       localStorage.clear();
            //       window.top.location.href = '../../login.html';
            //   }
            } catch (e) {}
  
            return data;
          }],
      });
  
      if (interceptors && interceptors.request) {
        ajax.interceptors.request.use(interceptors.request[0],
            interceptors.request[1]);
      }
  
      if (interceptors && interceptors.response) {
        ajax.interceptors.response.use(interceptors.response[0],
            interceptors.response[1]);
      }
  
      return ajax;
    }
  
    function createProxy(type, ajax, encap) {
      type = type || 'GET';
      return function(url) {
        if (type === 'GET'){
          return get(url, ajax, encap);
        } else if(type === 'post'){
          return post(url, ajax, encap);
        }
      };
    }
  
    // global config
    var __default_option = {
        headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'},
        withCredentials: false
    }
    var __request_interceptors = [
      function(config) {
        return config;
      },
      function(error) {
        return Promise.reject(error);
      },
    ];
    var __response_interceptors = [
      function(response) {
        return response;
      },
      function(error) {
        // TODO 在此可写请求失败后统一处理
        if (error.code === 'ECONNABORTED' && error.message.indexOf('timeout') > -1) {
          console.log("请求超时");
        } else {
          console.log("请求失败");
        }
        return Promise.reject(error);
      },
    ];
    var __encap_data = function(data) {
      if (is_object(data)) {
        var _data = new URLSearchParams();
        for (var key in data) {
          _data.append(key, (data[key] === null || data[key] === 'null' ? '' : data[key]));
        }
        return _data.toString();
      }
  
      return data;
    };
    var __encap_params = function(params) {
      // TODO : handle params here
      return params;
    };
    var __default_proxy = function(baseURL, type = "post", option = __default_option) {
      var ajax = createAjax(baseURL, option, {
        request: __request_interceptors,
        response: __response_interceptors
      });
      return createProxy(type, ajax, __encap_data);
    };
  
    platform[call] = {
      createAjax: createAjax,
      createProxy: createProxy,
      options: {
        headers: __default_option.headers,
        interceptors: {
          request: __request_interceptors,
          response: __response_interceptors,
        },
        encap: {
          data: __encap_data,
          params: __encap_params,
        },
      },
      defaultProxy: __default_proxy,
    };
  })(window, 'N');
  